package com.pgybook.front.action;

import com.google.common.collect.Maps;
import com.pgybook.db.entity.domain.Customer;
import com.pgybook.front.action.vo.LoginVO;
import com.pgybook.front.action.vo.RegVo;
import com.pgybook.front.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

import javax.validation.Valid;
import java.util.Map;

import static com.pgybook.front.web.util.FrontUtil.*;

@Controller
@RequestMapping("member")
public class LoginAct {
    private static final String LOGIN_Landing_Page = "/landing.html";
    private static final String LOGIN_Success_Page = "index";


    @RequestMapping("login.jspx")
    public String login(@Valid LoginVO loginVO, BindingResult br, ModelMap mmap, WebRequest wq) {
        if (br.hasErrors()) {
            Map<String, Object> param = Maps.newHashMap();
            for (FieldError fieldError : br.getFieldErrors()) {
                param.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return redirectPage(LOGIN_Landing_Page, param);
        }
        Customer cst = null;
        if (wq.getAttribute("custId", 1) != null) {
            Long custId = (Long) wq.getAttribute("custId", 1);
            cst = memberSrv.getCustomer(custId);
        } else if (memberSrv.login(loginVO.getEmail(), loginVO.getUserPwd())) {
            cst = memberSrv.getCustomer(loginVO.getEmail());
            wq.setAttribute(CUSTOMER_ID_KEY, cst.getCustid(), 1);
            wq.setAttribute("name", cst.getName(), 1);
        }
        if (cst != null) {
            return redirectAction("/member/index");
        }
        return "redirect:" + LOGIN_Landing_Page;
    }

    @RequestMapping("reg.jspx")
    public String register(@Valid RegVo regVo, BindingResult br, ModelMap mmap) {
        if (memberSrv.reg(regVo.getEmail(), regVo.getUserPwd(), regVo.getUserName())) {
            return "reg_sendMail";
        }
        return "reg_fail";
    }

    @Autowired
    private MemberService memberSrv;

    public void setMemberSrv(MemberService memberSrv) {
        this.memberSrv = memberSrv;
    }
}
